package com.ltxtiyu.video.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse;
import com.ltxtiyu.video.common.ConfigConstant;

import com.ltxtiyu.video.entity.Manager;
import com.ltxtiyu.video.entity.Moment;
import com.ltxtiyu.video.entity.Tag;
import com.ltxtiyu.video.service.ms.ConfigService;
import com.ltxtiyu.video.service.ms.VideoService;
import com.ltxtiyu.video.tool.AliVideoTool;
import com.ltxtiyu.video.tool.FileTool;
import com.ltxtiyu.video.tool.StringUtil;


import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("videoController")
@RestController
public class VideoController {


    @Reference
    private VideoService vs;
    @Reference
    private ConfigService configService;

    /**
     * 条件查询列表
     * @param page
     * @param limit
     * @param name
     * @param tag
     * @return
     */
    @RequestMapping(value = "paramlist",method = RequestMethod.GET)
    public ResponseEntity<Map<String ,Object>> paramlist(HttpServletRequest request, int page, int limit, String name, String tag){
        try {
            Manager loginUser = (Manager) request.getSession().getAttribute("loginUser");
            Map<String,Object> map = new HashMap<>();
            String userId = loginUser.getUserId();
            map.put("page",(page-1)*limit);
            map.put("row",limit);
            if(StringUtil.isNotBlank(name)){

                map.put("name",name);
            }
            if(StringUtil.isNotBlank(tag)){

                map.put("tag",tag);
            }
            Map<String,Object> result = vs.selectParamList(map,userId);

            return ResponseEntity.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

    }

    /**
     * 删除动态
     * @param id
     * @return
     */
    @RequestMapping(value = "delById")
    public ResponseEntity<Void> delById(Integer id){
        try {
            if (id.longValue() <1){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
            vs.delByID(id);

            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping("delByIds")
    @ResponseBody
    public  ResponseEntity delByIds(String ids){
        try {
            if (StringUtil.isNullOrEmpty(ids)){
                return new ResponseEntity(HttpStatus.BAD_REQUEST);
            }
            if (!ids.contains(",")) {
                vs.delByID(Integer.parseInt(ids));
            } else {
                String[] split = ids.split(",");
                for (String id : split) {
                    vs.delByID(Integer.parseInt(id));
                }
            }
            return new ResponseEntity(HttpStatus.NO_CONTENT);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 视频编辑标签
     * @param videoTags
     * @param videoId
     * @return
     */
    @RequestMapping(value = "updateTag")
    public ResponseEntity<Void> addTagByVideoId(String videoTags,Integer videoId){
        try {
            vs.addTagByVideoId(videoTags,videoId);
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }catch(Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新标题
     * @param contentText
     * @param momentId
     * @return
     */
    @RequestMapping(value = "updateContent")
    public ResponseEntity updateContent(String contentText,Integer momentId){
        try {
            Moment moment = new Moment();
            moment.setId(momentId);
            moment.setContentText(contentText);
            vs.updateMoment(moment);
            return  new ResponseEntity(HttpStatus.NO_CONTENT);
        }catch(Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     *  查询视频标签
     * @param videoId
     * @return
     */
    @RequestMapping(value = "queryTagByVideoId",method = RequestMethod.GET)
    public ResponseEntity<List<Tag>> queryTagByVideoId(Integer videoId){
        try {
            List<Tag> result = vs.findTagByVideoId(videoId);

            return ResponseEntity.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

    }

    /**
     * 上传视频
     * @return
     */
    @RequestMapping("uploadVideo")
    public ResponseEntity uploadVideo(MultipartFile file,Integer publisher) throws IOException {
        try {
            //
            if (publisher == null){
                Map<String,Object> result = new HashMap<>();
                result.put("code",1);
                return new ResponseEntity(result,HttpStatus.BAD_REQUEST);
            }
            String accessKeyId = configService.selectByCkey(ConfigConstant.ACCESSKEYID).getCvalue();
            String accessKeySecret = configService.selectByCkey(ConfigConstant.ACCESSKEYSECRET).getCvalue();
            String vodDomain = configService.selectByCkey(ConfigConstant.ALIVOD_URL).getCvalue();
            String alivodPlayAction = configService.selectByCkey(ConfigConstant.ALIVOD_PLAY_ACTION).getCvalue();
            AliVideoTool aliVideoTool = new AliVideoTool(accessKeyId, accessKeySecret, vodDomain, alivodPlayAction);

            String title = file.getName();
            String fileName=file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            Map<String, Object> map = aliVideoTool.uploadStream( accessKeyId,accessKeySecret,title,fileName,inputStream);
            String aliVideoId = (String) map.get("videoId");
            Moment moment = new Moment();
            moment.setPublisher(publisher);
            String fileNameNoEx = FileTool.getFileNameNoEx(fileName);
            moment.setContentText(fileNameNoEx);
            Map<String,Object> result = new HashMap<>();
            result.put("vidoeId",aliVideoId);
            result.put("name",fileName);
            Boolean  flag= vs.addVideo(moment,aliVideoId);
            if (flag){
                result.put("code",0);
                return new ResponseEntity(result,HttpStatus.CREATED);
            }else{
                Map<String,Object> error = new HashMap<>();
                result.put("code",0);
                result.put("msg","");
                result.put("data",null);
                return new ResponseEntity(error,HttpStatus.CREATED);

            }
        }catch (Exception e){
            Map<String,Object> result = new HashMap<>();
            result.put("code",-2);
            e.printStackTrace();
            return new ResponseEntity(result,HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     *  新增视频
     * @param moment
     * @return
     */
    @RequestMapping("addVideo")
    public ResponseEntity addVideo(String aliVideoId,Moment moment){
        try {
            if (StringUtil.isNullOrEmpty(aliVideoId)){
                 return new ResponseEntity(HttpStatus.BAD_REQUEST);
            }
           Boolean  flag= vs.addVideo(moment,aliVideoId);
            if (flag){

                return new ResponseEntity(HttpStatus.CREATED);
            }else{
                return new ResponseEntity(HttpStatus.NO_CONTENT);

            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     *  视频合成
     * @param videoInfos
     * @return
     */
    @RequestMapping("synthesisVideo")
    public ResponseEntity synthesisVideo(String videoInfos,Integer publisher,String contentText,String videoTail){
        String accessKeyId = configService.selectByCkey(ConfigConstant.ACCESSKEYID).getCvalue();
        String accessKeySecret = configService.selectByCkey(ConfigConstant.ACCESSKEYSECRET).getCvalue();
        String vodDomain = configService.selectByCkey(ConfigConstant.ALIVOD_URL).getCvalue();
        String alivodPlayAction = configService.selectByCkey(ConfigConstant.ALIVOD_PLAY_ACTION).getCvalue();
        AliVideoTool aliVideoTool = new AliVideoTool(accessKeyId, accessKeySecret, vodDomain, alivodPlayAction);
        try {
            String timeline = AliVideoTool.buildTimeline(videoInfos,videoTail);
            Map<String,Object> param = new HashMap<>();
            param.put("timeline", timeline);
            String firstId=videoInfos.split(",")[0];
            String coverURL = aliVideoTool.getVideoPlayUrl(firstId).get("CoverURL");
            param.put("mediaMetadata",AliVideoTool.buildMediaMetadata(coverURL));
            param.put("produceConfig",AliVideoTool.buildProduceConfig());
            String synthesisVideoId = aliVideoTool.synthesisVideo(param);
            if(StringUtil.isNotBlank(synthesisVideoId)){
                Moment moment = new Moment();
                moment.setPublisher(publisher);
                moment.setContentText(contentText);
                vs.addVideo(moment,synthesisVideoId);
                return new ResponseEntity(HttpStatus.CREATED);
            }else {
                return new ResponseEntity(HttpStatus.NO_CONTENT);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询视频信息
     * @param id
     * @return
     */
    @RequestMapping("queryVideo")
    public ResponseEntity queryVideo(String id){
        try {
            String accessKeyId = configService.selectByCkey(ConfigConstant.ACCESSKEYID).getCvalue();
            String accessKeySecret = configService.selectByCkey(ConfigConstant.ACCESSKEYSECRET).getCvalue();
            String vodDomain = configService.selectByCkey(ConfigConstant.ALIVOD_URL).getCvalue();
            String alivodPlayAction = configService.selectByCkey(ConfigConstant.ALIVOD_PLAY_ACTION).getCvalue();
            AliVideoTool aliVideoTool = new AliVideoTool(accessKeyId, accessKeySecret, vodDomain, alivodPlayAction);
            GetVideoInfoResponse.Video video = aliVideoTool.queryVideoInfo(id);
            return new ResponseEntity(video,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);

        }
    }




}
